package com.hserver.system.mapper;

import com.hserver.system.entity.PermissionEntity;
import com.hserver.system.entity.RoleEntity;
import com.hserver.system.entity.UserEntity;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserMapper {

    @Select("select * from sys_user where username = #{p.username}")
    UserEntity login(@Param("p") UserEntity param);

    @Select("select p.* from sys_permission p where p.id in (" +
            "select distinct p1.id from sys_permission p1 join sys_role_permission rp on p1.id=rp.permission_id " +
            "join sys_user_role ur on ur.role_id = rp.role_id " +
            "join sys_user u on u.id = ur.user_id " +
            "where u.username = #{p}" +
            ") order by p.sort_no")
    List<PermissionEntity> getUserPermission(@Param("p")String username);

    @Delete("delete from sys_token where create_by = #{p.username}")
    void logout(@Param("p")UserEntity param);

    int cont(@Param("p")UserEntity userEntity);

    List<UserEntity> list(@Param("p")UserEntity userEntity);

    @Options(useGeneratedKeys = true)
    @Insert("insert into sys_user(username,realname,password,birthday,sex,email,phone,status,del_flag)" +
            " value(#{p.username},#{p.realname},#{p.password},#{p.birthday},#{p.sex},#{p.email},#{p.phone},#{p.status},#{p.delFlag})")
    Integer insert(@Param("p")UserEntity userEntity);

    @Delete("delete from sys_user_role where user_id = #{p}")
    int delRole(@Param("p")Integer id);

    @Options(useGeneratedKeys = true)
    @Insert("insert into sys_user_role (user_id,role_id)" +
            " value(#{p},#{p1})")
    void insertRole(@Param("p")Integer userId,@Param("p1")Integer roleId);

    @Delete("delete from sys_user where id = #{p}")
    void deleteById(@Param("p")Integer id);

    @Update("update sys_user set username=#{p.username},realname=#{p.realname},password=#{p.password},birthday=#{p.birthday},sex=#{p.sex},email=#{p.email},phone=#{p.phone},status=#{p.status} where id=#{p.id}")
    void update(@Param("p")UserEntity userEntity);

    @Select("select r.* from sys_role r join sys_user_role ur on ur.role_id=r.id where ur.user_id = #{p}")
    List<RoleEntity> queryRole(@Param("p")Integer userid);

    @Select("SELECT LAST_INSERT_ID()")
    int getLastId();

}
